<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * @package       Pfw
 * @author        Sean Sitter <sean@picnicphp.com>
 * @copyright     2010 The Picnic PHP Framework
 * @license       http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link          http://www.picnicphp.com
 * @since         0.10
 * @filesource
 */

Pfw_Loader::loadClass("Pfw_Paginator");

class Pfw_Paginator_QueryObject extends Pfw_Paginator
{
    /**
     * @var Pfw_Model_QueryObject
     */
    protected $query_object;

    /**
     * @param Pfw_Model_QueryObject
     * @param int $page_num
     * @param int $per_page
     */
    public function  __construct($qo, $page_num, $per_page)
    {
        parent::__construct($page_num, $per_page);
        $this->query_object = clone $qo;
    }

    public function paginate() {
        if (!is_null($this->collection)) {
            return $this->collection;
        }

        $with = $this->query_object->_getRequestedWith();
        foreach ($with as $r => $w) {
            if ($w['join_strategy'] != 'Immediate') {
                continue;
            }
            $rel = $this->query_object->_getModelRelationship($r);
            if ($rel['count'] == Pfw_Model::ASSOC_MANY || 
                    $rel['count'] == Pfw_Model::ASSOC_HABTM)
            {
                throw new Pfw_Exception_Model(
                   "Pagination of one to many relationships with an immediate strategy
                    is not supported ({$r})"
                );
            }
        }

        $this->query_object->_getRequestedWith();
        $this->query_object->limit($this->getPerPage());
        $this->query_object->offset($this->getOffset());

        $this->collection = $this->query_object->exec();
        return $this->collection;
    }

    public function getTotal() {
        if (!is_null($this->total)) {
            return $this->total;
        }
        $this->total = $this->query_object->count();
        return $this->total;
    }
}

?>